<template>
  <div class="news">
    <div class="header">
      <!-- 搜索 -->
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="搜索周边新闻">
          <el-input
            v-model="formInline.news"
            placeholder="输入新闻标题进行搜索"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSearch">查询</el-button>
        </el-form-item>
      </el-form>
      <!-- 添加新闻按钮 -->
      <el-row>
        <el-button type="primary" round @click="onSubmit">添加新闻</el-button>
      </el-row>
    </div>
    <div class="main">
      <!-- table表格 -->
      <el-table :data="tableData" style="width: 100%">
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-form label-position="left" inline class="demo-table-expand">
              <el-form-item label="新闻编号">
                <span>{{ props.row.news_id }}</span>
              </el-form-item>
              <el-form-item label="新闻标题">
                <span>{{ props.row.news_tit }}</span>
              </el-form-item>
              <el-form-item label="新闻创建日期">
                <span>{{ props.row.news_date | dateFormat }}</span>
              </el-form-item>
              <el-form-item label="新闻的阅读量">
                <span>{{ props.row.news_num }}</span>
              </el-form-item>
              <el-form-item label="新闻的详细内容">
                <span>{{ props.row.news_desc }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column label="编号" prop="news_id"> </el-table-column>
        <el-table-column label="新闻标题" prop="news_tit"> </el-table-column>
        <!-- 在eleentui使用过滤器 -->
        <el-table-column label="发布时间" prop="news_date">
          <template slot-scope="scope">{{ scope.row.news_date | dateFormat }}</template>
        </el-table-column>
        <el-table-column label="详情" prop="news_desc"> </el-table-column>
        <el-table-column label="浏览量" prop="news_num"> </el-table-column>

        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="block">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="100"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>

      <!-- 弹出框 -->
      <div class="userModel">
        <div class="mask" v-show="userBoolean" @click="cancelModel"></div>
        <div class="content" :class="userBoolean ? 'userContent' : ''">
          <el-form
            :model="ruleForm"
            status-icon
            :rules="rules"
            ref="ruleForm"
            label-width="100px"
            class="demo-ruleForm"
          >
            <h3>{{ modelTitle }}一则新闻</h3>
            <el-form-item label="新闻编号" prop="newsId">
              <el-input v-model="ruleForm.newsId"></el-input>
            </el-form-item>

            <el-form-item label="新闻标题" prop="newsTit">
              <el-input v-model="ruleForm.newsTit"></el-input>
            </el-form-item>
            <el-form-item label="新闻详情" prop="newsDesc">
              <el-input v-model="ruleForm.newsDesc"></el-input>
            </el-form-item>
            <el-form-item label="新闻浏览量" prop="newsNum">
              <el-input v-model="ruleForm.newsNum"></el-input>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="submitForm('ruleForm')">{{
                modelTitle
              }}</el-button>
              <el-button @click="resetForm('ruleForm')">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  getNewsList,
  addNews,
  delNews,
  newsDetail,
  updateNews,
} from "../api/api";
import { Message } from "element-ui";
export default {
  // 定义属性
  name: "News",
  data() {
    //   校验新闻编号
    var checkAge = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入新闻编号"));
      }
      setTimeout(() => {
        console.log(value.length);
        if (value.length < 1 || value.length > 4) {
          callback(new Error("请输入1-4位的新闻编号"));
        } else {
          callback();
        }
      }, 100);
    };
    // 校验新闻标题
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入新闻标题"));
      } else {
        callback();
      }
    };
    // 校验新闻详情
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入新闻详情"));
      } else {
        callback();
      }
    };
    // 校验新闻浏览量
    var validateAddress = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入新闻浏览量"));
      } else {
        callback();
      }
    };
    return {
      tableData: [],
      formInline: {
        news: "",
      },
      userBoolean: false,
      ruleForm: {
        newsTit: "",
        newsDesc: "",
        newsId: "",
        newsNum: "",
      },
      rules: {
        newsTit: [{ validator: validatePass, trigger: "blur" }],
        newsDesc: [{ validator: validatePass2, trigger: "blur" }],
        newsId: [{ validator: checkAge, trigger: "blur" }],
        newsNum: [{ validator: validateAddress, trigger: "blur" }],
      },
      modelTitle: "添加",
      // news_id: null,
      total: 0,
      page: 1,
      size: 5,
    };
  },
  methods: {
    // 点击查询搜索新闻标题
    onSearch() {
      // console.log(this.formInline.news);
      this.getList();
    },
    // 查询新闻列表
    getList() {
      getNewsList({
        page: this.page,
        size: this.size,
        news_tit: this.formInline.news,
      }).then((res) => {
        // console.log(res);
        this.tableData = res.data;
        this.total = res.total;
      });
    },
    // 添加新闻
    // 点击添加，添加方法的验证
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // console.log(111)
          // console.log(this.ruleForm);
          if (this.modelTitle == "添加") {
            // 添加接口
            addNews({
              news_id: this.ruleForm.newsId,
              news_tit: this.ruleForm.newsTit,
              news_desc: this.ruleForm.newsDesc,
              news_num: this.ruleForm.newsNum,
            }).then((res) => {
              // console.log(res);
              if (res.code == 200) {
                Message({
                  message: "恭喜你，成功添加一则新闻！",
                  type: "success",
                });
                this.cancelModel();
                this.getList();
              }
            });
          } else if (this.modelTitle == "修改") {
            console.log(this.ruleForm);
            console.log(this.ruleForm.newsId);
            // 修改接口
            updateNews({
              news_id: this.ruleForm.newsId,
              news_tit: this.ruleForm.newsTit,
              news_desc: this.ruleForm.newsDesc,
              news_num: this.ruleForm.newsNum,
            }).then((res) => {
              // console.log(111);
              console.log(res);
              if (res.code == 200) {
                Message({
                  message: res.messages,
                  type: "success",
                });
                this.cancelModel();
                this.getList();
              }
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 点击编辑
    handleEdit(index, row) {
      console.log(index, row);
      // 查询详情接口
      newsDetail({ news_id: row.news_id }).then((res) => {
        console.log(111);
        console.log(res);
        if (res.code == 200) {
          this.ruleForm.newsId = res.data.news_id;
          this.ruleForm.newsTit = res.data.news_tit;
          this.ruleForm.newsDesc = res.data.news_desc;
          this.ruleForm.newsNum = res.data.news_num;

          this.modelTitle = "修改";
          this.userBoolean = true;
        }
      });
    },
    // 点击删除
    handleDelete(index, row) {
      // console.log(index, row);
      delNews({
        news_id: row.news_id,
      }).then((res) => {
        // console.log(res);
        if (res.code == 200) {
          Message({
            message: "恭喜你，删除成功！",
            type: "success",
          });
          this.tableData.splice(index, 1);
        }
      });
    },
    // 添加显示模态窗口
    onSubmit() {
      // console.log("submit!");
      this.modelTitle = "添加";
      this.userBoolean = true;
    },
    // 关闭模态窗口，清空内容
    cancelModel() {
      this.userBoolean = false;
      // 重置表单
      this.$refs["ruleForm"].resetFields();
    },
    // 点击重置，清空数据的方法
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 点击条数
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.size = val;
      this.getList();
    },
    // 点击页码
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.page = val;
      this.getList();
    },
  },
  filters: {
    // 私有过滤时间的方法
    dateFormat(date) {
      // console.log(date);
      var dt = new Date(date);
      // 获取年
      var y = dt.getFullYear();
      // console.log(y)
      // 获取月
      var m = (dt.getMonth() + 1).toString().padStart(2, "0");
      // m = m < 10 ? "0" + m : m
      // console.log(m);
      // 获取日
      var d = dt.getDate().toString().padStart(2, "0");
      // d = d < 10 ? "0" + d : d
      // console.log(d);
      // 获取时
      var hh = dt.getHours().toString().padStart(2, "0");
      // hh = hh < 10 ? "0" + hh : hh
      // 获取分
      var mm = dt.getMinutes().toString().padStart(2, "0");
      // mm = mm < 10 ? "0" + mm : mm
      // 获取秒
      var ss = dt.getSeconds().toString().padStart(2, "0");
      // ss = ss < 10 ? "0" + ss : ss;
      return `${y} - ${m} - ${d}  ${hh} : ${mm} : ${ss}`;
    },
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getList();
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
};
</script>

<style lang='scss' scoped>
.news {
  width: 100%;
  .header {
    display: flex;
    justify-content: space-between;
    padding: 30px;
  }
  .main {
    .demo-table-expand {
      font-size: 0;
      padding: 10px 270px;
    }
    .demo-table-expand label {
      width: 90px;
      color: #99a9bf;
    }
    .demo-table-expand .el-form-item {
      margin-right: 0;
      margin-bottom: 0;
      width: 50%;
    }
    ::v-deep .el-table .cell {
      box-sizing: border-box;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: normal;
      word-break: break-all;
      line-height: 23px;
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
      padding-right: 10px;
    }

    .block {
      padding: 30px;
    }
  }
  // 弹出框样式
  .userModel {
    .mask {
      position: fixed;
      left: 0;
      top: 0;
      z-index: 99;
      width: 100%;
      height: 100%;
      background-color: rgba(0, 0, 0, 0.4);
    }
    .content {
      position: absolute;
      left: 50%;
      top: 0;
      transform: translateX(-50%);
      z-index: 100;
      background-color: #fff;
      transition: 0.5s;
      opacity: 0;
      padding: 30px 60px;
      border-radius: 10px;
      visibility: hidden;
      h3 {
        margin-bottom: 15px;
      }
      ::v-deep .el-form-item__label:before {
        content: "";
      }
    }
    .userContent {
      top: 15%;
      opacity: 1;
      visibility: visible;
    }
  }
}
</style>